package models

import (
	"log"
	"time"
)

type OaUserRole struct {
	Id        int
	UserId    int
	RoleId    int
	CreatorId int
	AddTime   time.Time
}

func (o *OaUserRole) GetUserRoleByRoleId(id string) (role OaRole, err error) {
	_, err = engine.Table("oa_user_role").Alias("ur").
		Select("r.role_action").
		Join("LEFT", []string{"oa_user", "u"}, "u.id = ur.creator_id").
		Join("LEFT", []string{"oa_role", "r"}, "r.id = ur.role_id").
		Where("ur.role_id = ?", id).Get(&role)
	return role, err
}

type OaUserList struct {
	Id        int    `json:"id"`
	Name      string `json:"name"`
	RoleName  string `json:"role_name"`
	Creator   string `json:"creator"`
	CreatTime string `json:"creat_time"`
}

func (o *OaUserRole) GetUserRoleList(pageSize, offset int) (count int64, list []OaUserList, err error) {
	err = engine.Table("oa_user_role").Alias("ur").
		Select("ur.id,r.name as role_name,u.name,c.name as creator,ur.add_time as creat_time").
		Join("LEFT", []string{"oa_user", "u"}, "u.id = ur.user_id").
		Join("LEFT", []string{"oa_role", "r"}, "r.id = ur.role_id").
		Join("LEFT", []string{"oa_user", "c"}, "c.id = ur.creator_id").
		//Where("r.status = ?", "1").
		Limit(pageSize, offset).Desc("ur.id").Find(&list)
	count, _ = engine.Table("oa_user_role").Alias("ur").
		Join("LEFT", []string{"oa_user", "u"}, "u.id = ur.user_id").
		Join("LEFT", []string{"oa_role", "r"}, "r.id = ur.role_id").
		Join("LEFT", []string{"oa_user", "c"}, "c.id = ur.creator_id").
		Count()
	// log.Println(err, list)
	return
}

func (o *OaUserRole) GetUserRoleByUserId(id int) (role OaRole, err error) {
	_, err = engine.Table("oa_user_role").Alias("ur").
		Select("r.role_action").
		Join("LEFT", []string{"oa_user", "u"}, "u.id = ur.creator_id").
		Join("LEFT", []string{"oa_role", "r"}, "r.id = ur.role_id").
		Where("ur.user_id = ?", id).Get(&role)
	return role, err
}

func (o *OaUserRole) GetRoleByCondition(id int) (has bool, users OaUserRole, err error) {

	has, err = engine.Table("oa_user_role").Where("uid = ?", id).Get(&users)
	return
}

func (o *OaUserRole) Add() bool {
	if _, err := engine.Table("oa_user_role").Insert(o); err != nil {
		log.Println(err)
		return false
	}
	return true
}
